package com.huahai.utils;

import org.springframework.session.SessionRepository;
import org.springframework.session.web.http.SessionRepositoryFilter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Objects;

/**
 * redis session 工具类
 */
public class RedisSessionUtil {
    /**
     * 通过 sessionId 删除 redis 里的 session
     * @param request
     * @param sessionId
     */
    public static void removeRedisSession(HttpServletRequest request, String sessionId) {
        HttpSession session = request.getSession();
        if (Objects.equals(sessionId, session.getId())) {
            session.invalidate();
            return;
        }
        Object sessionRepositoryAttribute = request.getAttribute(SessionRepositoryFilter.SESSION_REPOSITORY_ATTR);
        if (sessionRepositoryAttribute == null) {
            return;
        }
        SessionRepository<?> sessionRepository = (SessionRepository<?>) sessionRepositoryAttribute;
        if (sessionRepository.findById(sessionId) == null) {
            return;
        }
        sessionRepository.deleteById(sessionId);
    }

    /**
     * 获取sessionId
     * @param request
     */
    public static String getSessionId(HttpServletRequest request) {
        return request.getSession().getId();
    }

}
